package com.example.comfortableweather.ui.me

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.comfortableweather.R
import com.example.comfortableweather.WeatherApplication
import com.example.comfortableweather.base.BaseBindingFragment
import com.example.comfortableweather.databinding.FragmentMeBinding
import com.example.comfortableweather.storage.TokenPreferences
import com.example.comfortableweather.ui.login.LoginActivity
import com.example.comfortableweather.util.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [MeFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class MeFragment : BaseBindingFragment<FragmentMeBinding>() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getUserInfo()
    }

    private fun getUserInfo() {
        lifecycleScope.launch(Dispatchers.Main) {
            val res = withContext(Dispatchers.IO) {
                RetrofitClient.apiService.getUserInfoApi()
            }
            // 检查响应码是否为10000（表示成功）
            if (res.code == 10000) {
                Toast.makeText(requireContext(), "获取用户信息成功", Toast.LENGTH_SHORT).show()
                val userData = res.data
                // 确保 Fragment 处于活跃状态且 binding 已初始化
//                if (isAdded && !isDetached && isBindingInit()) {
                binding.tvAccount.text = userData?.username
                binding.tvGender.text = userData?.gender
                binding.tvNickname.text = userData?.nick_name
                binding.tvSignature.text = userData?.motto
                loadAvatar(userData?.avatar ?: "")
                if (userData != null) {
                    WeatherApplication.getInstance()?.initUser(userData)
                }
//                }
            } else {
                Toast.makeText(requireContext(), "获取用户信息失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun loadAvatar(url: String) {
        lifecycleScope.launch {
            // 确保 Fragment 处于活跃状态且 binding 已初始化
            if (isAdded && !isDetached && isBindingInit()) {
                Glide.with(this@MeFragment)
                    .load(url)
                    .apply(
                        RequestOptions()
                            .circleCrop()
                            .placeholder(R.mipmap.avatar1)
                            .error(R.mipmap.avatar1)
                    )
                    .into(binding.ivAvatar)
            }
        }
    }

    override fun initBinding(
        inflater: LayoutInflater,
        parent: ViewGroup?
    ): FragmentMeBinding {
        return FragmentMeBinding.inflate(inflater, parent, false)
    }

//    override fun onCreateView(
//        inflater: LayoutInflater, container: ViewGroup?,
//        savedInstanceState: Bundle?
//    ): View? {
//        // Inflate the layout for this fragment
////        super.onCreateView(inflater, container, savedInstanceState)
//
//        return inflater.inflate(R.layout.fragment_me, container, false)
//    }

    override fun initView() {
        // 确保 Fragment 处于活跃状态且 binding 已初始化
        if (isAdded && !isDetached && isBindingInit()) {
            // 退出登录
            binding.btnLogout.setOnClickListener {
                // 清空token
                TokenPreferences.getInstance(requireContext()).clearToken()
                // 跳转到登录页面
                val intent = Intent(requireContext(), LoginActivity::class.java)
                startActivity(intent)
            }
        }
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment MeFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            MeFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}